import {getLogger} from '@siteed/react-native-logger';
import {Toast} from 'teaset';
const logger = getLogger('App');

import axios from 'axios';
import {ActivityIndicator} from 'react-native';
// 创建一个新的axios实例
const instance = axios.create({
  baseURL: '', // 基础URL
  timeout: 10000, // 请求超时时间（毫秒）
  headers: {}, // 自定义请求头
});
let customKey: null = null;
interface HttpResult {
  msg: string;
  success: boolean;
  code: string;
  data: object;
}

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    // 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断
    config.params = {
      ...config.params,
      timestamp: new Date().getTime() / 1000,
    };
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    if (customKey) {
      Toast.hide(customKey);
      customKey = null;
    }
    logger.info('request: ', response.request._url);
    logger.info('response.data: ', response.data);
    if (response.status === 200) {
      if (response.data && response.data.code === '10000') {
        return Promise.resolve(response.data);
      }
      return Promise.reject(new Error(response.data.msg));
    } else {
      return Promise.reject(new Error('网络错误，请重启网络或者服务器'));
    }
  },
  // 服务器状态码不是200的情况
  error => {
    if (customKey) {
      Toast.hide(customKey);
      customKey = null;
    }
    console.log('request error:', error.response);
    console.log('request error request:', error.request);
    if (error.response && error.response.status) {
      switch (error.response.status) {
        // 401: 未登录
        // 未登录则跳转登录页面，并携带当前页面的路径
        // 在登录成功后返回当前页面，这一步需要在登录页操作。
        case 401:
          break;
        // 403 token过期
        // 登录过期对用户进行提示
        // 清除本地token和清空vuex中token对象
        // 跳转登录页面
        case 403:
          break;

        // 404请求不存在
        case 404:
          break;
        // 其他错误，直接抛出错误提示
        default:
      }
    }
    return Promise.reject(new Error('网络错误，请重启网络或者服务器'));
  },
);

export function setHeaders(headers: object) {
  instance.defaults.headers = {...instance.defaults.headers, ...headers};
}

export function setBaseURL(url: string) {
  instance.defaults.baseURL = url;
}

export function getBaseURL() {
  return instance.defaults.baseURL;
}

export function request(
  method: string,
  url: string,
  params: object,
  headers: object,
): Promise<HttpResult> {
  // 使用实例发送请求
  return new Promise((resolve, reject) => {
    logger.info('request url: ' + url);
    logger.info('request params: ' + JSON.stringify(params));
    instance
      .request({
        url: url,
        method: method,
        data: params,
        headers: headers,
      })
      .then(
        res => {
          // @ts-ignore
          resolve(res);
        },
        err => {
          reject(err);
        },
      );
  });
}

export function post(
  url: string,
  params: any,
  loading?: boolean,
): Promise<HttpResult> {
  if (loading) {
    if (!customKey) {
      customKey = Toast.show({
        icon: <ActivityIndicator size="large" color={'white'} />,
        position: 'center',
        duration: 1000000,
        modal: true,
      });
    }
  }
  // 使用实例发送请求
  return new Promise((resolve, reject) => {
    logger.info('post url: ' + url);
    logger.info('post params: ' + JSON.stringify(params));
    instance
      .post(url, params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
      .then(
        res => {
          // @ts-ignore
          resolve(res);
        },
        err => {
          reject(err);
        },
      );
  });
}

export function postForm(
  url: string,
  params: any,
  loading?: boolean,
): Promise<HttpResult> {
  if (loading) {
    if (!customKey) {
      customKey = Toast.show({
        icon: <ActivityIndicator size="large" color={'white'} />,
        position: 'center',
        duration: 1000000,
        modal: true,
      });
    }
  }
  // 使用实例发送请求
  return new Promise((resolve, reject) => {
    logger.info('post url: ' + url);
    logger.info('post params: ' + JSON.stringify(params));
    instance
      .post(url, params, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then(
        res => {
          // @ts-ignore
          resolve(res);
        },
        err => {
          reject(err);
        },
      );
  });
}

export function get(url: string, params?: any): Promise<HttpResult> {
  // 使用实例发送请求
  return new Promise((resolve, reject) => {
    logger.info('url: ' + url);
    logger.info('params: ' + JSON.stringify(params));
    instance
      .get(url, {
        params: params,
      })
      .then(
        res => {
          // console.log('res: ' + JSON.stringify(res));
          // @ts-ignore
          resolve(res);
        },
        err => {
          // console.log('err: ' + JSON.stringify(err));
          reject(err);
        },
      );
  });
}
let injections = {};

export function injectApi(name: string, injection: object) {
  if (injections[name] || injections[name] === 0) {
    const old = injections[name];
    instance.interceptors.request.eject(old);
  }
  injections[name] = instance.interceptors.request.use(
    config => {
      injection && injection(config);
      return config;
    },
    error => {
      // 对请求错误做些什么
      return Promise.reject(error);
    },
  );
}

export function rejectApi(name) {
  if (injections[name] || injections[name] === 0) {
    const old = injections[name];
    instance.interceptors.request.eject(old);
    injections[name] = null;
  }
}
